<template>
  <div class="order-detail">
    <!-- 订单详情 -->
    <van-sticky>
      <nav-bar style="background: var(--theme-color); color: white" is-back>
        <template #center>订单详情</template>
        <template #right>
          <i class="iconfont icon-gengduo"></i>
        </template>
      </nav-bar>
    </van-sticky>
    <div style="height: 80px; background: var(--theme-color)"></div>
    <div class="order-detail-body">
      <van-contact-card
        type="edit"
        :name="currentContact.name"
        :tel="currentContact.tel"
        @click="onEdit"
      />
      <div class="goods">
        <template v-if="!oid">
          <div class="item" v-for="item in orderList" :key="item.id">
            <img :src="item.goods.show.img" />
            <div class="title">{{ item.goods.title }}</div>
            <div class="price">
              <span>{{ item.goods.price | priceFilter }}</span>
              <div>x {{ item.num }}</div>
            </div>
          </div>
          <div class="sub-price">
            <span>商品金额</span>
            <span>{{ totalPrice | priceFilter }}</span>
          </div>
          <div class="total-price">
            实付金额：{{ totalPrice | priceFilter }}
          </div>
        </template>
        <template v-else>
          <div
            class="item"
            v-for="(item, index) in order.orderDescs"
            :key="index"
          >
            <img :src="item.show.img" />
            <div class="title">{{ item.title }}</div>
            <div class="price">
              <span>{{ item.price | priceFilter }}</span>
              <div>x {{ item.num }}</div>
            </div>
          </div>
          <div class="sub-price">
            <span>商品金额</span>
            <span>{{ order.totalPrice | priceFilter }}</span>
          </div>
          <div class="total-price">
            实付金额：{{ order.totalPrice | priceFilter }}
          </div>
        </template>
      </div>
      <div
        v-if="oid"
        class="order-info"
        style="
          background: white;
          padding: 15px;
          margin-top: 10px;
          font-size: 12px;
          border-radius: 10px;
        "
      >
        <div style="font-weight: 700; line-height: 35px">订单信息</div>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: var(--gray-moderate);
          "
        >
          <div style="flex: 1">
            订单编号：{{ order.id }}
            <div>下单时间：{{ order.createDateTime | parseTime }}</div>
          </div>
          <span style="width: 30px">复制</span>
        </div>
      </div>
    </div>
    <div class="handler">
      <van-button class="btn" size="small" round>联系客服</van-button>
      <van-button
        class="btn"
        size="small"
        round
        plain
        color="var(--theme-color)"
        @click="handleSaveOrder"
        v-if="!oid"
        >添加订单</van-button
      >
      <van-button
        class="btn"
        size="small"
        round
        plain
        v-if="oid && order.status == 0"
        @click="handleCancel(oid)"
      >
        取消
      </van-button>
      <van-button
        class="btn"
        size="small"
        round
        color="red"
        v-if="oid && order.status == 0"
        @click="handlePay(oid)"
      >
        去支付
      </van-button>
      <van-button
        class="btn"
        size="small"
        round
        color="red"
        v-if="oid && (order.status == 1 || order.status == 2)"
        @click="handleDelete(oid)"
      >
        删除
      </van-button>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapState } from 'vuex'
import {
  queryGoodsById,
  saveOrder,
  deleteCart,
  queryOrderById,
  pay,
  cancel,
  delCart
} from '@/api'
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
  components: {
    NavBar
  },
  data: () => ({
    // [{gid,num}]
    info: [],
    // 购物车id
    cIds: [],
    oid: null,
    order: {},
    // 商品数据
    orderList: [],
    // 联系人信息
    currentContact: {
      name: '张三',
      tel: '13000000000'
    }
  }),
  mounted() {
    const { oid } = this.$route.params
    if (oid) {
      this.oid = oid
      this.queryOrderById()
    } else {
      const { info, cIds } = this.$route.query
      if (info) this.info = JSON.parse(info)
      if (cIds) this.cIds = JSON.parse(cIds)
      this.queryGoodsById()
    }
  },
  computed: {
    totalPrice() {
      return this.orderList.reduce(
        (pre, el) => pre + el.goods.price * el.num,
        0
      )
    },
    ...mapState({
      uid: (state) => state.userInfo.id
    })
  },
  methods: {
    // 查询商品数据
    async queryGoodsById() {
      for (const info of this.info) {
        const goods = await queryGoodsById(info.gid)
        this.orderList.push({ goods, num: info.num })
      }
    },
    onEdit() {
      this.$router.push('/select-address')
    },
    // 添加订单
    async handleSaveOrder() {
      await saveOrder({
        uid: this.uid,
        address: '陕西省西安市雁塔区长风国际广场B座1510室',
        info: this.info
      })
      if (this.cIds.length > 0) await deleteCart({ id: this.cIds })
      this.$router.replace('/order')
    },
    // 根据订单id查询订单信息
    async queryOrderById() {
      this.order = await queryOrderById(this.oid)
    },
    // 支付
    async handlePay(id) {
      await pay({ id })
      this.$router.replace('/order')
    },
    // 取消订单
    async handleCancel(id) {
      await cancel({ id })
      this.$router.replace('/order')
    },
    // 删除订单
    async handleDelete(id) {
      await delCart(id)
      this.$router.replace('/order')
    }
  },
  filters: {
    priceFilter(price) {
      return price ? '￥' + price.toFixed(2) : ''
    },
    parseTime(time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    }
  }
}
</script>

<style lang="less" scoped>
.order-detail {
  min-height: 100vh;
  padding-bottom: 20px;
}
.order-detail-body {
  margin-top: -50px;
  padding: 0 15px;
  box-sizing: border-box;
}

.van-contact-card {
  padding: 15px;
  border-radius: 10px;
}

.goods {
  margin-top: 10px;
  background: white;
  border-radius: 10px;
  .item {
    display: flex;
    align-items: center;
    font-size: 12px;
    padding: 15px;
    img,
    .price {
      width: 60px;
      height: 60px;
    }
    .price {
      text-align: right;
      height: 100%;
      display: flex;
      flex-direction: column;
      align-self: center;
    }
    .title {
      margin-left: 10px;
      flex: 1;
      word-break: break-all;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 20px;
    }
  }
}

.sub-price {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  font-size: 14px;
  border-bottom: 1px solid var(--gray-shallow);
}

.total-price {
  text-align: right;
  padding: 15px;
  font-weight: 700;
  font-size: 14px;
}

.handler {
  box-sizing: border-box;
  padding: 5px 15px;
  width: 100%;
  background: white;
  position: fixed;
  bottom: 0;
  text-align: right;
  .btn {
    margin-right: 10px;
  }
}
</style>
